/**
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { Ref, ref } from 'vue';
import { DataGridProps } from '../data-grid.props';
import { UseRow, UseSelection, VisualData, VisualDataType } from './types';

export function useRow(
    props: DataGridProps,
    selectionCompostion: UseSelection,
    visibleDatas: Ref<VisualData[]>
): UseRow {
    const identifyField = ref(props.idField);
    const { setSelectionRow } = selectionCompostion;

    const hoverIndex = ref(-1);

    const selectedId = ref('');

    function gridRowClass(dataItem: VisualData) {
        const classObject = {
            'fv-grid-row': dataItem.type === VisualDataType.data,
            'fv-grid-group-row': dataItem.type === VisualDataType.group,
            'fv-grid-summary-row': dataItem.type === VisualDataType.summary,
            'fv-grid-row-hover': dataItem.index === hoverIndex.value,
            'fv-grid-row-selected': dataItem.data[identifyField.value].data === selectedId.value,
            'fv-grid-row-odd': dataItem.dataIndex % 2 > 0,
            'fv-grid-row-even': dataItem.dataIndex % 2 === 0
        } as Record<string, boolean>;
        return classObject;
    }

    function onClickRow($event: MouseEvent, dataItem: VisualData) {
        selectedId.value = dataItem.data[identifyField.value].data;
        setSelectionRow(visibleDatas, selectedId.value);
    }

    function onMouseoverRow($event: MouseEvent, dataItem: VisualData) {
        hoverIndex.value = dataItem.index;
    }

    function sidebarRowClass(dataItem: VisualData) {
        const classObject = {
            'fv-grid-sidebar-row': true,
            'fv-grid-sidebar-row-hover': dataItem.index === hoverIndex.value,
            'fv-grid-sidebar-row-selected': dataItem.data[identifyField.value].data === selectedId.value,
            'fv-grid-sidebar-row-odd': dataItem.dataIndex % 2 > 0,
            'fv-grid-sidebar-row-even': dataItem.dataIndex % 2 === 0
        } as Record<string, boolean>;
        return classObject;
    }

    return { gridRowClass, onClickRow, onMouseoverRow, sidebarRowClass };
}
